package vista;

import java.util.Arrays;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import controlador.PersonaControlador;
import modelo.Persona;

public class PersonaPrincipal {
	
	public Shell shellppal;
	private Table table;
	private PersonaControlador persctrl;
	private Composite compositeDetalle;
	private Composite compositePersona;
	public Text nombreText,apellidoText,tutorText,dniText,telText,celText,
	correoText,correoAltText,locText,colText,depText,obsText,equipoText,dniCuilText,preCuilText,subCuilText;
	public Combo cargoCombo;
	private String[] cargos = {"ALUMNO","DOCENTE","DIRECTOR","ADMINISTRADOR","TUTOR","OTRO"};
	private Label notificacionesLabel;
	public String boton_guardar = "NUEVO";
	private int filaSel;
	
	public PersonaPrincipal(Shell shell) {
		super();
		// TODO Auto-generated constructor stub
		this.shellppal = shell;
	}
	
	
	
	/**
	 * @wbp.parser.entryPoint
	 */
	public void initUI(){
//		Display display = Display.getDefault();
//		shellppal = new Shell();		
//		shellppal.setSize(788, 526);
		SashForm sashForm = new SashForm(shellppal, SWT.VERTICAL);
		sashForm.setBounds(0, 0, 783, 500);
		
		persctrl = new PersonaControlador();
				
		compositePersona = new Composite(sashForm, SWT.BORDER);
		GridLayout gl_compositePersona = new GridLayout(1, false);
		gl_compositePersona.verticalSpacing = 0;
		gl_compositePersona.marginWidth = 0;
		gl_compositePersona.marginHeight = 0;
		gl_compositePersona.horizontalSpacing = 0;
		compositePersona.setLayout(gl_compositePersona);
		
		Composite personaToolBar = new Composite(compositePersona, SWT.NONE);
		personaToolBar.setLayout(new GridLayout(4, false));
		personaToolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		
		Button nuevaPersonaButton = new Button(personaToolBar, SWT.NONE);
		Button editaPersonaButton = new Button(personaToolBar, SWT.NONE);
		Button eliminarPersonaButton = new Button(personaToolBar, SWT.NONE);
		notificacionesLabel = new Label(personaToolBar, SWT.LEFT);
		
		nuevaPersonaButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				limpiarDetalle();
				boton_guardar = "NUEVO";
				dniText.setEnabled(true);
			}
		});
		nuevaPersonaButton.setText("Nuevo...");
		
				
		editaPersonaButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				filaSel = table.getSelectionIndex();
				if(filaSel >= 0){					
					Persona per =  persctrl.getPersona(table.getItem(filaSel).getText(2));
					limpiarDetalle();
					cargarDetalle(per);
					dniText.setEnabled(false);
					boton_guardar = "ACTUALIZAR";
				}else{
					notificacionesLabel.setText("Debe seleccionar un Alumno de la lista!");					
					notificacionesLabel.pack();
				}
			}
		});
		editaPersonaButton.setText("Editar");
		
		eliminarPersonaButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int filaEliminar = table.getSelectionIndex();
				
				if(filaEliminar >= 0){
					 MessageBox messageBox = new MessageBox(PersonaPrincipal.this.shellppal, SWT.ICON_WARNING | SWT.YES | SWT.NO);				        
				        messageBox.setText("Aviso");
				        messageBox.setMessage("¿Esta Seguro que desea Eliminar?");
				        int buttonID = messageBox.open();
				        switch(buttonID) {
				        	case SWT.YES:
				        		if(persctrl.eliminarPersona(table.getItem(filaEliminar).getText(2)))
				        			table.remove(filaEliminar);
				        		else{
				        			notificacionesLabel.setText("No se pudo eliminar");
				        			notificacionesLabel.pack();
				        		}
				        		
				        }
					
				}else{
					notificacionesLabel.setText("Debe seleccionar un Alumno de la lista!");					
					notificacionesLabel.pack();
				}
			}
		});
		eliminarPersonaButton.setText("Eliminar");
		
		Color blue = shellppal.getDisplay().getSystemColor(SWT.COLOR_BLUE);
		notificacionesLabel.setForeground(blue);
		notificacionesLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		
				
		//creacion de la tabla
		table = new Table(compositePersona, SWT.BORDER | SWT.FULL_SELECTION);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		table.setBounds(0, 0, 32, 43);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		TableColumn tblclmnNombre = new TableColumn(table, SWT.NONE);
		tblclmnNombre.setWidth(100);
		tblclmnNombre.setText("Nombre");
		
		TableColumn tblclmnApellido = new TableColumn(table, SWT.NONE);
		tblclmnApellido.setWidth(100);
		tblclmnApellido.setText("Apellido");
		
		TableColumn tblclmnDni = new TableColumn(table, SWT.NONE);
		tblclmnDni.setWidth(100);
		tblclmnDni.setText("Dni");
		
		TableColumn tblclmnCuil = new TableColumn(table, SWT.NONE);
		tblclmnCuil.setWidth(100);
		tblclmnCuil.setText("Cuil");
		
		TableColumn tblclmnTutor = new TableColumn(table, SWT.NONE);
		tblclmnTutor.setWidth(100);
		tblclmnTutor.setText("Tutor");
		
		TableColumn tblclmnEquipo = new TableColumn(table, SWT.NONE);
		tblclmnEquipo.setWidth(100);
		tblclmnEquipo.setText("Equipo");
		
		TableColumn tblclmnCargo = new TableColumn(table, SWT.NONE);
		tblclmnCargo.setWidth(100);
		tblclmnCargo.setText("Cargo");
		
		inicializarTabla();

		
		compositeDetalle = new Composite(sashForm, SWT.BORDER);
		compositeDetalle.setLayout(new GridLayout(4, false));
		
//		FormData detalleData = new FormData();
//		detalleData.right = new FormAttachment(98);
//		detalleData.bottom = new FormAttachment(95);
//		compositeDetalle.setLayoutData(detalleData);
		
		
		Label descripcionLabel = new Label(compositeDetalle, SWT.NONE);
		//descripcionLabel.setBounds(0, 0, 57, 13);
		descripcionLabel.setText("Descripcion:");
		new Label(compositeDetalle, SWT.NONE);
		new Label(compositeDetalle, SWT.NONE);
		new Label(compositeDetalle, SWT.NONE);
		
		final Label nombrelabel = new Label(compositeDetalle, SWT.NONE);
		nombrelabel.setText("Nombre:");

		nombreText = new Text(compositeDetalle, SWT.BORDER);
		nombreText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		nombreText.setTextLimit(35);
		
		final Label apellidoLabel = new Label(compositeDetalle, SWT.NONE);
		apellidoLabel.setText("Apellido:");

		apellidoText = new Text(compositeDetalle, SWT.BORDER);
		apellidoText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		apellidoText.setTextLimit(35);

		final Label cargoLabel = new Label(compositeDetalle, SWT.NONE);
		cargoLabel.setText("Cargo:");
		
		cargoCombo = new Combo(compositeDetalle, SWT.DROP_DOWN | SWT.READ_ONLY);
		cargoCombo.setItems(cargos);
		cargoCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		cargoCombo.select(0);
		//cargoCombo.
		
		final Label tutorLabel = new Label(compositeDetalle, SWT.NONE);
		tutorLabel.setText("Tutor:");
		
		Composite tutorGroup = new Composite(compositeDetalle, SWT.NONE);
		GridData gd_tutorGroup = new GridData(SWT.LEFT, SWT.FILL, true, false, 1, 1);
		gd_tutorGroup.heightHint = 26;
		tutorGroup.setLayoutData(gd_tutorGroup);
		GridLayout gl_tutorGroup = new GridLayout(2, false);
		gl_tutorGroup.marginWidth = 0;
		gl_tutorGroup.verticalSpacing = 0;
		gl_tutorGroup.marginHeight = 1;
		tutorGroup.setLayout(gl_tutorGroup);

		tutorText = new Text(tutorGroup, SWT.BORDER);
		tutorText.setTextLimit(8);
		GridData gd_tutorText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_tutorText.widthHint = 54;
		tutorText.setLayoutData(gd_tutorText);
		tutorText.addVerifyListener(new VerifyListener(){
			public void verifyText(VerifyEvent event) {				
			    PersonaPrincipal.this.verificaEsNumero(event);
		}});
		
		Button selectTutorButton = new Button(tutorGroup, SWT.RIGHT);
		selectTutorButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		selectTutorButton.setText("Seleccionar...");
		selectTutorButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				(new BuscarTutor(shellppal)).buscarTutor(tutorText);				
	        }
	    });
				
		final Label dniLabel = new Label(compositeDetalle, SWT.NONE);
		dniLabel.setText("Dni:");

		dniText = new Text(compositeDetalle, SWT.BORDER);
		GridData gd_dniText = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_dniText.widthHint = 54;
		dniText.setLayoutData(gd_dniText);
		dniText.setTextLimit(8);
		dniText.setToolTipText("Ingrese el DNI sin puntos");
		
		dniText.addVerifyListener(new VerifyListener(){
			public void verifyText(VerifyEvent event) {				
			    PersonaPrincipal.this.verificaEsNumero(event);
		}});
		
		dniText.addModifyListener(new ModifyListener() {
			
			@Override
			public void modifyText(ModifyEvent event) {
				// TODO Auto-generated method stub				
				dniCuilText.setText(dniText.getText());				
			}
		});
		
		final Label cuilLabel = new Label(compositeDetalle, SWT.NONE);
		cuilLabel.setText("Cuil:");

		Composite cuilGroup = new Composite(compositeDetalle, SWT.NONE);
		GridData gd_cuilGroup = new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1);
		gd_cuilGroup.heightHint = 26;
		cuilGroup.setLayoutData(gd_cuilGroup);
		GridLayout gl_cuilGroup = new GridLayout(5, false);
		gl_cuilGroup.marginWidth = 0;
		gl_cuilGroup.verticalSpacing = 0;
		gl_cuilGroup.marginHeight = 1;
		cuilGroup.setLayout(gl_cuilGroup);		

		
		//prefijo
		preCuilText = new Text(cuilGroup, SWT.BORDER);
		GridData gd_preCuilText = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_preCuilText.widthHint = 12;
		preCuilText.setLayoutData(gd_preCuilText);
		preCuilText.setTextLimit(2);
		preCuilText.addVerifyListener(new VerifyListener(){
			public void verifyText(VerifyEvent event) {			 
			    PersonaPrincipal.this.verificaEsNumero(event);
		}});
		
		// primer guión
		final Label cuilLabel1 = new Label(cuilGroup, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.CENTER);
		GridData gd_cuilLabel1 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_cuilLabel1.widthHint = 7;
		cuilLabel1.setLayoutData(gd_cuilLabel1);
		//dni
		dniCuilText = new Text(cuilGroup, SWT.BORDER);
		dniCuilText.setTextLimit(8);
		GridData gd_dniCuilText = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_dniCuilText.widthHint = 56;
		dniCuilText.setLayoutData(gd_dniCuilText);
		dniCuilText.setEnabled(false);
		
		// segundo guión
		final Label cuilLabel2 = new Label(cuilGroup, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.CENTER);
		GridData gd_cuilLabel2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_cuilLabel2.widthHint = 7;
		cuilLabel2.setLayoutData(gd_cuilLabel2);
		//sufijo
		subCuilText = new Text(cuilGroup, SWT.BORDER);
		subCuilText.setTextLimit(1);
		GridData gd_subCuilText = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_subCuilText.widthHint = 7;
		subCuilText.setLayoutData(gd_subCuilText);
		subCuilText.addVerifyListener(new VerifyListener(){
			public void verifyText(VerifyEvent event) {			 
			    PersonaPrincipal.this.verificaEsNumero(event);
		}});
		
		//subCuilText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		
		final Label telLabel = new Label(compositeDetalle, SWT.NONE);
		telLabel.setText("Telefono:");

		telText = new Text(compositeDetalle, SWT.BORDER);
		telText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		telText.setTextLimit(12);
		telText.setToolTipText("Ingrese el numero de Telefono (ej: 03755-786345)");
		
		final Label celLabel = new Label(compositeDetalle, SWT.NONE);
		celLabel.setText("Celular:");

		celText = new Text(compositeDetalle, SWT.BORDER);
		celText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		celText.setTextLimit(15);
		celText.setToolTipText("Ingrese el numero de celular (ej: 03755-15-786345)");
		
		final Label correoLabel = new Label(compositeDetalle, SWT.NONE);
		correoLabel.setText("Correo:");

		correoText = new Text(compositeDetalle, SWT.BORDER);
		correoText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		correoText.setTextLimit(50);
		correoText.setToolTipText("Ingrese uan direccion de correo valida");
				
		final Label correoAltLabel = new Label(compositeDetalle, SWT.NONE);
		correoAltLabel.setText("Correo alt.:");

		correoAltText = new Text(compositeDetalle, SWT.BORDER);
		correoAltText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		correoAltText.setTextLimit(50);
		correoAltText.setToolTipText("Ingrese una direccion de correo alternativa");
		
		final Label colLabel = new Label(compositeDetalle, SWT.NONE);
		colLabel.setText("Direccion:");

		colText = new Text(compositeDetalle, SWT.BORDER);
		colText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		colText.setTextLimit(50);
		colText.setToolTipText("Ingrese la direccion y cualquier otro dato de ayuda");
		
		final Label locLabel = new Label(compositeDetalle, SWT.NONE);
		locLabel.setText("Localidad:");

		locText = new Text(compositeDetalle, SWT.BORDER);
		locText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		locText.setTextLimit(50);
		locText.setToolTipText("Ingrese la localidad");
		
		final Label depLabel = new Label(compositeDetalle, SWT.NONE);
		depLabel.setText("Departamento:");

		depText = new Text(compositeDetalle, SWT.BORDER);
		depText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		depText.setTextLimit(50);
				
		final Label obsLabel = new Label(compositeDetalle, SWT.NONE);
		obsLabel.setText("Obs.:");

		obsText = new Text(compositeDetalle, SWT.BORDER);
		obsText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		obsText.setTextLimit(200);
		obsText.setToolTipText("Ingrese una observacion hasta 200 caracteres");

		final Label equipoLabel = new Label(compositeDetalle, SWT.NONE);
		equipoLabel.setText("Equipo:");
		
		Composite equipoGroup = new Composite(compositeDetalle, SWT.NONE);
		GridData gd_equipoGroup = new GridData(SWT.LEFT, SWT.FILL, true, false, 1, 1);
		gd_equipoGroup.heightHint = 26;
		equipoGroup.setLayoutData(gd_equipoGroup);
		GridLayout gl_equipoGroup = new GridLayout(2, false);
		gl_equipoGroup.marginWidth = 0;
		gl_equipoGroup.verticalSpacing = 0;
		gl_equipoGroup.marginHeight = 1;
		equipoGroup.setLayout(gl_equipoGroup);

		equipoText = new Text(equipoGroup, SWT.BORDER);
		equipoText.setTextLimit(12);
		GridData gd_equipoText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_equipoText.widthHint = 84;
		equipoText.setLayoutData(gd_equipoText);
		//debería verificar que sea hexa

		equipoText.addVerifyListener(new VerifyListener(){
			public void verifyText(VerifyEvent event) {			 
			    PersonaPrincipal.this.verificaEsHexa(event);
		}});
		
		Button selectEquipoButton = new Button(equipoGroup, SWT.RIGHT);
		selectEquipoButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		selectEquipoButton.setText("Seleccionar...");		
			
		selectEquipoButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				(new BuscarEquipo(shellppal)).buscarEquiposSinAsignar(equipoText);				
	        }
	    });

		new Label(compositeDetalle, SWT.NONE);
				
		Button guardarButton = new Button(compositeDetalle, SWT.RIGHT);
		guardarButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		guardarButton.setText("Guardar");		
		guardarButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                Persona per = persctrl.guardarPersona(PersonaPrincipal.this);
                if (!(per == null )){
                	if(boton_guardar.equals("ACTUALIZAR")){
                		table.remove(filaSel);
                	}
                	TableItem item = new TableItem(table, SWT.NONE, 0);
            		item = personaAItemTable(per, item);
        			limpiarDetalle();
                }                	
            }
        });
								
		sashForm.setWeights(new int[] {220, 246});
		
	}
	
	private void inicializarTabla(){
		table.removeAll();
		List<Object> personas = persctrl.listarPersonas();		
		for (Object persona : personas) {
			TableItem item = new TableItem(table, SWT.NONE, 0);
			item = personaAItemTable((Persona) persona, item);			
		}		
	}
	
	private TableItem personaAItemTable(Persona per, TableItem item){
			item.setText(0, per.getNombre());
			item.setText(1, per.getApellido());
			item.setText(2, String.valueOf(per.getDni()));
			item.setText(3,per.getCuil());
			item.setText(4, String.valueOf(per.getTutor()));
			item.setText(5, "");
			item.setText(6, per.getCargo());
			return item;				
	}
	
	private void limpiarDetalle(){		
		nombreText.setText("");
		apellidoText.setText("");
		tutorText.setText("");
		dniText.setText("");
		preCuilText.setText("");
		subCuilText.setText("");
		telText.setText("");
		celText.setText("");
		correoText.setText("");
		correoAltText.setText("");
		locText.setText("");
		colText.setText("");
		depText.setText("");
		obsText.setText("");
		equipoText.setText("");
		cargoCombo.select(0);		
	}
	
	private void cargarDetalle(Persona per){
		nombreText.setText(per.getNombre());
		apellidoText.setText(per.getApellido());
		tutorText.setText(String.valueOf(per.getTutor()));
		dniText.setText(String.valueOf(per.getDni()));
		dniCuilText.setText(dniText.getText());
		String per_cuil = per.getCuil();
		if(per_cuil.length() >= 10 ){
			preCuilText.setText(per_cuil.substring(0,2));
			subCuilText.setText(per_cuil.substring(per_cuil.length()-1));
		}
		telText.setText(per.getTel_fijo());
		celText.setText(per.getTel_movil());
		correoText.setText(per.getCorreo());
		correoAltText.setText(per.getCorreo_alt());
		locText.setText(per.getLocalidad());
		colText.setText(per.getColonia());
		depText.setText(per.getDepartamento());
		obsText.setText(per.getObservaciones());
		equipoText.setText(per.getNombre());
		cargoCombo.select(Arrays.binarySearch(cargos, per.getCargo()));		
	}
	
	public void verificaEsNumero(VerifyEvent event) {			 
	    // Assume we don't allow it
		event.doit = false;		
				
	    // Get the character typed
	    char myChar = event.character;
	   
	    String text = ((Text) event.widget).getText();	   
	 
	    // Allow 0-9
	   if (Character.isDigit(myChar)) event.doit = true;
	   
	   // permitir numero cuando setText
	   
	   if(this.isIntNumber(event.text)) event.doit = true;	  
	 
	   // Allow backspace y clear
	   if (myChar == '\b' || event.text.equals("")) {		   
		   event.doit = true;
	   }
	}
	
	public boolean isIntNumber(String num){
	    try{
	        Integer.parseInt(num);
	    } catch(NumberFormatException nfe) {
	        return false;
	    }
	    return true;
	}
	
	public void verificaEsHexa(VerifyEvent event) {			 
	    // Assume we don't allow it
		event.doit = false;		
				
	    // Get the character typed
	    char myChar = event.character;
	   
	    String text = ((Text) event.widget).getText();	   
	 
	    // permitir numero cuando setText
	   
	   if(this.isHex(event.text)) event.doit = true;	  
	 
	   // Allow backspace y clear
	   if (myChar == '\b' || event.text.equals("")) {		   
		   event.doit = true;
	   }
	}
	public boolean isHex(String num){
		return num.matches("[0-9A-Fa-f]+");
	}
	
	public void setNotificacion(String noti){
		notificacionesLabel.setText(noti);
		notificacionesLabel.pack();
	}
}
